package com.member.mp.web;

import com.member.common.core.domain.R;
import com.member.common.core.page.PageResult;
import com.member.mp.web.user.SupperController;
import com.member.shop.domain.SysBizUser;
import com.member.shop.service.ISysBizUserService;
import com.member.common.core.page.TableDataInfo;
import com.member.common.utils.PageUtils;
import com.member.mp.aop.DistributeLock;
import com.member.shop.domain.SysBizRaffleActivity;
import com.member.shop.domain.SysBizRaffleActivityPrize;
import com.member.shop.domain.SysBizRafflePrize;
import com.member.shop.domain.SysBizRaffleResults;
import com.member.shop.service.ISysBizRaffleActivityPrizeService;
import com.member.shop.service.ISysBizRaffleActivityService;
import com.member.shop.service.ISysBizRafflePrizeService;
import com.member.shop.service.ISysBizRaffleResultsService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * 抽奖奖品Controller
 *
 * @author lxc
 * @date 2024-03-13
 */
@RestController()
@Api(value = "抽奖接口", tags = {"抽奖接口"})
@Slf4j
@RequestMapping("/wx/raffle")
public class RafflePrizeController extends SupperController {
    @Resource
    private ISysBizRafflePrizeService sysBizRafflePrizeService;

    @Resource
    private ISysBizRaffleActivityService sysBizRaffleActivityService;

    @Resource
    private ISysBizRaffleActivityPrizeService sysBizRaffleActivityPrizeService;

    @Resource
    private ISysBizRaffleResultsService sysBizRaffleResultsService;
    @Autowired
    private ISysBizUserService userService;


    /**
     * 根据活动id获取奖品信息
     */
    @RequestMapping(value = "/prizeByActivityId", method = RequestMethod.GET)
    @ApiOperation(value = "根据活动id获取奖品信息")
    @ResponseBody
    public R<SysBizRaffleActivity> prizeByActivityId(@RequestParam(name = "activityId") Long activityId) {
        try {
            SysBizRaffleActivity sysBizRaffleActivity = sysBizRaffleActivityService.selectSysBizRaffleActivityById(activityId);
            List<SysBizRafflePrize> sysBizRaffleActivities = sysBizRaffleActivityService.prizeByActivityId(activityId);
            sysBizRaffleActivity.setSysBizRafflePrize(sysBizRaffleActivities);
            return R.ok(sysBizRaffleActivity);
        } catch (Exception e) {
            log.error("我的推荐列表数据异常, error => ", e);
            return R.fail(e.getMessage());
        }
    }






    /**
     * 抽奖
     */
    @RequestMapping(value = "/lottery", method = RequestMethod.GET)
    @ApiOperation(value = "抽奖")
    @ResponseBody
    @DistributeLock(prefix = "PACKAGE_LOTTERY", cacheKey = "PACKAGE:LOTTERY:LOCK:", appendUserId = true, lockTime = 10)
    public R<SysBizRaffleResults> lottery(@RequestParam(name = "activityId") Long activityId) {
        try {
            //当前用户
            Long uid = this.getLoginUser().getId();
            //活动信息
            SysBizRaffleActivity sysBizRaffleActivity = sysBizRaffleActivityService.selectSysBizRaffleActivityById(activityId);

            //过滤出有库存的奖品
            List<SysBizRafflePrize> sysBizRaffleActivities = sysBizRaffleActivityService.prizeByActivityId(activityId);

            //判断逻辑（查看最多参与次数、每天参与次数、最多中奖次数）
            Long maxParticipationCount = sysBizRaffleActivity.getMaxParticipationCount();
            Long dailyParticipationCount = sysBizRaffleActivity.getDailyParticipationCount();
            Long maxWinningCount = sysBizRaffleActivity.getMaxWinningCount();

            List<SysBizRaffleResults> sysBizRaffleResults = sysBizRaffleResultsService.selectByActivitId(sysBizRaffleActivity.getId(), uid);
            if (!sysBizRaffleResults.isEmpty()) {
                //判断查看最多参与次数
                if (sysBizRaffleResults.size() >= maxParticipationCount) {
                    return R.notFound("已到达最多参与次数");
                }

                //每天参与次数
                SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd");
                String dateTime = dft.format(new Date());
                // 过滤出今天的数据
                List<SysBizRaffleResults> todayResults = sysBizRaffleResults.stream().filter(result -> dft.format(result.getCreateTime()).equals(dateTime)).collect(Collectors.toList());
                if (!todayResults.isEmpty() && todayResults.size() >= dailyParticipationCount) {
                    return R.notFound("每天参与次数已用完");
                }

                //判断最多中奖次数
                Long[] filteredArray = sysBizRaffleResults.stream().map(SysBizRaffleResults::getPrizeId).toArray(Long[]::new);

                List<SysBizRafflePrize> SysBizRafflePrizes = sysBizRafflePrizeService.selecIsPrizeList(filteredArray);
                if (!SysBizRafflePrizes.isEmpty() && todayResults.size() >= maxWinningCount) {
                    return R.notFound("已达到最多中奖次数");
                }
            }

            //概率模式
            if (sysBizRaffleActivity.getRaffleType() == 1) {

                Long[] options = new Long[sysBizRaffleActivities.size()];
                double[] probabilities = new double[sysBizRaffleActivities.size()];

                for (int i = 0; i < sysBizRaffleActivities.size(); i++) {
                    options[i] = sysBizRaffleActivities.get(i).getPrizeId();
                    probabilities[i] = Double.parseDouble(sysBizRaffleActivities.get(i).getPrizeProbability());
                }
                //返回中奖奖品的id
                Long winningOption = drawLottery(options, probabilities);


                //判断奖品库存
                SysBizRaffleActivityPrize sysBizRaffleActivityPrize = new SysBizRaffleActivityPrize();
                sysBizRaffleActivityPrize.setActivityId(sysBizRaffleActivity.getId());
                sysBizRaffleActivityPrize.setPrizeId(winningOption);
                List<SysBizRaffleActivityPrize> sysBizRaffleActivityPrizes = sysBizRaffleActivityPrizeService.selectSysBizRaffleActivityPrizeList(sysBizRaffleActivityPrize);
                if (sysBizRaffleActivityPrizes != null) {
                    Long prizeAmount = sysBizRaffleActivityPrizes.get(0).getPrizeAmount();
                    //说明有库存
                    if (prizeAmount != null && prizeAmount > 0) {
                        sysBizRaffleActivityPrizes.get(0).setPrizeAmount(prizeAmount - 1);
                        boolean b = sysBizRaffleActivityPrizeService.updateById(sysBizRaffleActivityPrizes.get(0));
                    } else {
                        return R.notFound("该商品已没有库存");
                    }
                }

                SysBizRafflePrize sysBizRafflePrize = sysBizRafflePrizeService.selectSysBizRafflePrizeByPrizeId(winningOption);
                SysBizRaffleResults sysBizRaffleResults1 = new SysBizRaffleResults();
                sysBizRaffleResults1.setUserId(uid);
                sysBizRaffleResults1.setPrizeId(sysBizRafflePrize.getPrizeId());
                sysBizRaffleResults1.setActivityId(sysBizRaffleActivity.getId());
                sysBizRaffleResults1.setUserName(this.getLoginUser().getNickName());
                sysBizRaffleResults1.setPrizeName(sysBizRafflePrize.getPrizeName());
                sysBizRaffleResults1.setIsPrize(sysBizRafflePrize.getIsPrize());
                sysBizRaffleResults1.setPrizeType(sysBizRafflePrize.getPrizeType());
                sysBizRaffleResults1.setPrizeImage(sysBizRafflePrize.getPrizeImage());
                sysBizRaffleResults1.setPrizeDetails(sysBizRafflePrize.getPrizeDetails());
                sysBizRaffleResults1.setPrizeAmount(sysBizRafflePrize.getPrizeAmount());
                sysBizRaffleResults1.setTitle(sysBizRaffleActivity.getTitle());
                sysBizRaffleResults1.setSubtitle(sysBizRaffleActivity.getSubtitle());
                int i = sysBizRaffleResultsService.insertSysBizRaffleResults(sysBizRaffleResults1);
                if (sysBizRafflePrize.getPrizeType() == 1) {
                    SysBizUser sysBizUser = userService.selectSysBizUserById(this.getLoginUser().getId());
                    if (sysBizUser != null && sysBizUser.getScore() != null) {
                        sysBizUser.setScore(sysBizUser.getScore() + sysBizRafflePrize.getPrizeAmount());
                    }
                    userService.updateById(sysBizUser);
                }
                if (sysBizRafflePrize.getPrizeType() == 2) {


                }
                if (sysBizRafflePrize.getPrizeType() == 3) {
//                    sysBizRaffleResults1.setPhone();
//                    sysBizRaffleResults1.setProvince();
//                    sysBizRaffleResults1.setCity();
//                    sysBizRaffleResults1.setArea();
//                    sysBizRaffleResults1.setName();
//                    sysBizRaffleResults1.setDetails();
                }
                return R.ok(sysBizRaffleResults1);
            }

            return R.ok(null);
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail(e.getMessage());
        }
    }

    public static Long drawLottery(Long[] options, double[] probabilities) {
        double totalProbability = 0;
        for (double probability : probabilities) {
            totalProbability += probability;
        }

        Random random = new Random();
        double randomNumber = random.nextDouble() * totalProbability;

        System.out.println(randomNumber);
        double accumulatedProbability = 0;
        Long winningOption = null;
        for (int i = 0; i < options.length; i++) {
            accumulatedProbability += probabilities[i];
            if (randomNumber <= accumulatedProbability) {
                winningOption = options[i];
                break;
            }
        }

        return winningOption;
    }


    /**
     * 根据活动id获取中奖结果
     */
    @RequestMapping(value = "/prizeResult", method = RequestMethod.GET)
    @ApiOperation(value = "根据活动id获取中奖结果")
    @ResponseBody
    public R<List<SysBizRaffleResults>> prizeResult(@RequestParam(name = "activityId") Long activityId) {
        try {

            SysBizRaffleResults sysBizRaffleResults = new SysBizRaffleResults();
            sysBizRaffleResults.setActivityId(activityId);
            sysBizRaffleResults.setUserId(this.getLoginUser().getId());
            List<SysBizRaffleResults> sysBizRaffleResults1 = sysBizRaffleResultsService.selectSysBizRaffleResultsList(sysBizRaffleResults);
            return R.ok(sysBizRaffleResults1);
        } catch (Exception e) {
            log.error("我的推荐列表数据异常, error => ", e);
            return R.fail(e.getMessage());
        }
    }
}
